<?php


namespace app\admin\controller;


use app\admin\model\User;
use app\BaseController;
use think\facade\Cache;
use think\facade\View;
use think\captcha\facade\Captcha;
use app\admin\validate\LoginValidate;
use think\Response;
use think\response\Json;

/**
 * 登录控制器
 *
 * Class LoginController
 * @package app\admin\controller
 */
class LoginController extends BaseController
{

    /**
     * 登录页面
     *
     * @return string
     */
    public function index(): string
    {

        return View::fetch('/login');
    }

    /**
     * 返回验证码
     * 配置可在app/config/captcha修改
     *
     * @return \think\Response
     */
    public function verify(): Response
    {
        return Captcha::create();
    }

    /**
     * 登录操作
     *
     * @param LoginValidate $validator
     * @return \think\response\Json
     */
    public function dologin(LoginValidate $validator): Json
    {

        $param = $this->request->param();
//        $validator->batch(true);
        $isValid = $validator->check($param);

        if (!$isValid) {

            $this->error($validator->getError());

        }

        $userModel = new User();

        $user = $userModel->checkUser($param['user_name']);
        if (empty($user)) {
            $this->error('用户不存在');
        }

        if (sha1($param['password'] . $user->pass_salt) != $user->password) {
            $this->error('密码不正确');
        }

        if (1 != $user->status) {
            $this->error('该账号被禁用');
        }

        session('username', $user->user_name);
        session('id', $user->id);
        session('head', $user->head);
        session('role', $user->role_name);
        session('role_id', $user->role_id);
        session('rule', $user->rule);

        // 更新管理员状态
        $user->login_times     = +1;
        $user->last_login_ip   = request()->ip();
        $user->last_login_time = time();
        $user->save();

        return json(msg(1, (string)url('index/index'), '登录成功'));

    }


    /**
     * 退出登录
     */
    public function loginOut()
    {
        session('username', null);
        session('id', null);
        session('head', null);
        session('role', null);  // 角色名
        session('role_id', null);
        session('rule', null);

        Cache::clear();

        redirect(url('index'))->send();
        exit();
    }


}